package com.sencorsta.ids.account.http.phone;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.sencorsta.ids.account.http.common.EmbedServerVerify;
import com.sencorsta.ids.common.information.ErrorCodeList;
import com.sencorsta.ids.common.service.MysqlService;
import com.sencorsta.ids.common.service.RedisService;
import com.sencorsta.ids.core.log.Out;
import com.sencorsta.ids.core.tcp.http.HttpHandler;
import com.sencorsta.utils.string.Md5Tools;
import com.sencorsta.utils.string.StringUtil;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.http.FullHttpRequest;

/**
* @description: 忘记密码
* @author TAO
* @date 2019/12/12 18:27
*/
public class UpdatePassWord extends HttpHandler implements RedisService {
    @Override
    public String doPost(ChannelHandlerContext ctx, FullHttpRequest request, JSONObject params) {
        Out.debug("------------------忘记密码------ForgetPassWord-------------------");
        String phone = params.getString("phone");
        String newPassword = params.getString("newPassword");
        String oldPassword = params.getString("oldPassword");

        //判断电话号码的用户是否存在
        {
            String sql="SELECT `phone_password` FROM `account` WHERE `phone`=?";
            Object[] args=new Object[]{
                    phone
            };
            JSONArray result=MysqlService.getInstance().select(sql,args);
            JSONObject jsz=JSONObject.parseObject(String.valueOf(result.get(0)));
            if (jsz.keySet().size()>0){
                String pws=jsz.getString("phone_password");
                if (!Md5Tools.MD5(oldPassword).equals(pws)){
                    return error(ErrorCodeList.OLD_PWA_IS_ERROR);
                }
            }else{
                return error(ErrorCodeList.LOGIN_ACC_NOT_FIND);
            }
        }

        //开始修改密码
        {
            String sql="UPDATE `account` SET `phone_password`=? WHERE `phone`=?";
            Object[] args=new Object[]{
                    Md5Tools.MD5(newPassword),phone
            };
            if (!MysqlService.getInstance().update(sql,args)){
                return error(ErrorCodeList.UPDATE_PWA_IS_ERROR);
            }
        }
        return success();
    }

    @Override
    public String doGet(ChannelHandlerContext ctx, FullHttpRequest request, JSONObject params) {
        return doPost(ctx, request, params);
    }

    @Override
    public Boolean getValidate(ChannelHandlerContext ctx, FullHttpRequest request, JSONObject params) {
        return EmbedServerVerify.Verify(params);
    }

    @Override
    public String getPath() {
        return "/Account/UpdatePassWord";
    }
}
